package com.demo.petshop.service.impl;

import com.demo.petshop.entity.ProductReviews;
import com.demo.petshop.entity.Products;
import com.demo.petshop.mapper.ProductReviewsMapper;
import com.demo.petshop.mapper.ProductsMapper;
import com.demo.petshop.service.ProductReviewsService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.demo.petshop.entity.table.ProductReviewsTableDef.PRODUCT_REVIEWS;
import static com.demo.petshop.entity.table.ProductsTableDef.PRODUCTS;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@Service
public class ProductReviewsServiceImpl extends ServiceImpl<ProductReviewsMapper, ProductReviews> implements ProductReviewsService {

    @Autowired
    private ProductReviewsMapper productReviewsMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Override
    public List<ProductReviews> getByProductId(Integer productId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(PRODUCT_REVIEWS.PRODUCT_ID.eq(productId))
                .orderBy(PRODUCT_REVIEWS.REVIEW_ID, false);
        return list(queryWrapper);
    }

    @Override
    public ProductReviews getByOrderId(Integer orderId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(PRODUCT_REVIEWS.ORDER_ID.eq(orderId));
        return getOne(queryWrapper);
    }

    @Override
    public List<ProductReviews> getByUserId(Integer userId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(PRODUCT_REVIEWS.USER_ID.eq(userId))
                .orderBy(PRODUCT_REVIEWS.CREATED_AT.desc());
        return list(queryWrapper);
    }

    @Override
    public Object saveReviews(ProductReviews productReviews) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select(PRODUCTS.ALL_COLUMNS).from(PRODUCTS)
                .where(PRODUCTS.PRODUCT_ID.eq(productReviews.getProductId()));
        Products products = productsMapper.selectOneByQuery(queryWrapper);
        products.setReviewCount(products.getReviewCount()+1);
        productsMapper.update(products);
        return productReviewsMapper.insert(productReviews);
    }
}
